
// shooting_game/frontend/game.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 游戏状态
let gameRunning = false;
let gamePaused = false;
let score = 0;
let level = 1;
let lives = 3;
let highScore = localStorage.getItem('highScore') || 0;

// 玩家设置
const player = {
  x: canvas.width / 2 - 25,
  y: canvas.height - 60,
  width: 50,
  height: 50,
  speed: 5,
  color: '#00ff00',
  bullets: [],
  weapon: 'laser',
  lastShot: 0,
  shootDelay: 300
};

// 敌人设置
const enemies = [];
const enemySettings = {
  spawnRate: 1000,
  lastSpawn: 0,
  speed: 2,
  health: 1,
  size: 40
};

// 武器设置
const weapons = {
  laser: {
    damage: 1,
    speed: 10,
    color: '#00ffff',
    width: 3,
    height: 15,
    delay: 300
  },
  flame: {
    damage: 0.5,
    speed: 8,
    color: '#ff6600',
    width: 8,
    height: 20,
    delay: 100
  },
  bomb: {
    damage: 3,
    speed: 6,
    color: '#ff0000',
    width: 10,
    height: 10,
    delay: 1000
  }
};

// 控制设置
const keys = {
  ArrowUp: false,
  ArrowDown: false,
  ArrowLeft: false,
  ArrowRight: false,
  w: false,
  a: false,
  s: false,
  d: false,
  ' ': false
};

// 初始化游戏
function initGame() {
  gameRunning = true;
  gamePaused = false;
  score = 0;
  lives = 3;
  level = 1;
  player.bullets = [];
  enemies.length = 0;
  updateUI();
  gameLoop();
}

// 游戏主循环
function gameLoop(timestamp) {
  if (!gameRunning || gamePaused) return;
  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 更新玩家
  updatePlayer();
  drawPlayer();
  
  // 更新子弹
  updateBullets();
  drawBullets();
  
  // 生成敌人
  spawnEnemies(timestamp);
  
  // 更新敌人
  updateEnemies();
  drawEnemies();
  
  // 检测碰撞
  checkCollisions();
  
  // 检查关卡升级
  checkLevelUp();
  
  requestAnimationFrame(gameLoop);
}

// 玩家控制
function updatePlayer() {
  if (keys.ArrowLeft || keys.a) player.x = Math.max(0, player.x - player.speed);
  if (keys.ArrowRight || keys.d) player.x = Math.min(canvas.width - player.width, player.x + player.speed);
  if (keys.ArrowUp || keys.w) player.y = Math.max(0, player.y - player.speed);
  if (keys.ArrowDown || keys.s) player.y = Math.min(canvas.height - player.height, player.y + player.speed);
  
  // 射击
  if (keys[' '] && Date.now() - player.lastShot > weapons[player.weapon].delay) {
    shoot();
    player.lastShot = Date.now();
  }
}

function drawPlayer() {
  ctx.fillStyle = player.color;
  ctx.fillRect(player.x, player.y, player.width, player.height);
  
  // 绘制武器指示器
  ctx.fillStyle = weapons[player.weapon].color;
  ctx.fillRect(player.x + player.width/2 - 5, player.y - 10, 10, 10);
}

function shoot() {
  const weapon = weapons[player.weapon];
  player.bullets.push({
    x: player.x + player.width/2 - weapon.width/2,
    y: player.y,
    width: weapon.width,
    height: weapon.height,
    speed: weapon.speed,
    color: weapon.color,
    damage: weapon.damage
  });
}

// 子弹逻辑
function updateBullets() {
  for (let i = player.bullets.length - 1; i >= 0; i--) {
    const bullet = player.bullets[i];
    bullet.y -= bullet.speed;
    
    // 移除超出屏幕的子弹
    if (bullet.y + bullet.height < 0) {
      player.bullets.splice(i, 1);
    }
  }
}

function drawBullets() {
  player.bullets.forEach(bullet => {
    ctx.fillStyle = bullet.color;
    ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
  });
}

// 敌人逻辑
function spawnEnemies(timestamp) {
  if (timestamp - enemySettings.lastSpawn > enemySettings.spawnRate) {
    const size = enemySettings.size;
    enemies.push({
      x: Math.random() * (canvas.width - size),
      y: -size,
      width: size,
      height: size,
      speed: enemySettings.speed + level * 0.2,
      color: `hsl(${Math.random() * 360}, 70%, 50%)`,
      health: enemySettings.health + Math.floor(level / 3)
    });
    enemySettings.lastSpawn = timestamp;
    enemySettings.spawnRate = Math.max(200, 1000 - level * 50);
  }
}

function updateEnemies() {
  for (let i = enemies.length - 1; i >= 0; i--) {
    const enemy = enemies[i];
    enemy.y += enemy.speed;
    
    // 移除超出屏幕的敌人
    if (enemy.y > canvas.height) {
      enemies.splice(i, 1);
      lives--;
      updateUI();
      if (lives <= 0) {
        gameOver();
      }
    }
  }
}

function drawEnemies() {
  enemies.forEach(enemy => {
    ctx.fillStyle = enemy.color;
    ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
    
    // 绘制血条
    if (enemy.health > 1) {
      ctx.fillStyle = 'red';
      ctx.fillRect(enemy.x, enemy.y - 10, enemy.width, 5);
      ctx.fillStyle = 'green';
      ctx.fillRect(enemy.x, enemy.y - 10, enemy.width * (enemy.health / (enemySettings.health + Math.floor(level / 3))), 5);
    }
  });
}

// 碰撞检测
function checkCollisions() {
  // 子弹与敌人碰撞
  for (let i = player.bullets.length - 1; i >= 0; i--) {
    const bullet = player.bullets[i];
    for (let j = enemies.length - 1; j >= 0; j--) {
      const enemy = enemies[j];
      if (isColliding(bullet, enemy)) {
        enemy.health -= bullet.damage;
        player.bullets.splice(i, 1);
        
        if (enemy.health <= 0) {
          enemies.splice(j, 1);
          score += 10 * level;
          updateUI();
        }
        break;
      }
    }
  }
  
  // 玩家与敌人碰撞
  enemies.forEach(enemy => {
    if (isColliding(player, enemy)) {
      lives--;
      updateUI();
      if (lives <= 0) {
        gameOver();
      }
    }
  });
}

function isColliding(obj1, obj2) {
  return obj1.x < obj2.x + obj2.width &&
         obj1.x + obj1.width > obj2.x &&
         obj1.y < obj2.y + obj2.height &&
         obj1.y + obj1.height > obj2.y;
}

// 游戏状态管理
function checkLevelUp() {
  const nextLevel = Math.floor(score / 1000) + 1;
  if (nextLevel > level) {
    level = nextLevel;
    updateUI();
  }
}

function gameOver() {
  gameRunning = false;
  if (score > highScore) {
    highScore = score;
    localStorage.setItem('highScore', highScore);
  }
  alert(`游戏结束! 得分: ${score}\n最高分: ${highScore}`);
  updateUI();
}

// 事件监听
document.addEventListener('keydown', (e) => {
  if (keys.hasOwnProperty(e.key)) keys[e.key] = true;
});

document.addEventListener('keyup', (e) => {
  if (keys.hasOwnProperty(e.key)) keys[e.key] = false;
});

// 武器切换
document.getElementById('weapon1').addEventListener('click', () => {
  player.weapon = 'laser';
  updateWeaponUI();
});

document.getElementById('weapon2').addEventListener('click', () => {
  player.weapon = 'flame';
  updateWeaponUI();
});

document.getElementById('weapon3').addEventListener('click', () => {
  player.weapon = 'bomb';
  updateWeaponUI();
});

function updateWeaponUI() {
  document.querySelectorAll('.weapon-btn').forEach(btn => {
    btn.classList.remove('active');
  });
  document.getElementById(`weapon${player.weapon === 'laser' ? 1 : player.weapon === 'flame' ? 2 : 3}`).classList.add('active');
}

// 游戏控制按钮
document.getElementById('startBtn').addEventListener('click', initGame);
document.getElementById('pauseBtn').addEventListener('click', () => {
  if (gameRunning) {
    gamePaused = !gamePaused;
    document.getElementById('pauseBtn').textContent = gamePaused ? '▶️ 继续' : '⏸️ 暂停';
    if (!gamePaused) gameLoop();
  }
});

// UI更新函数 (与ui.js交互)
function updateUI() {
  document.getElementById('score').textContent = score;
  document.getElementById('level').textContent = level;
  document.getElementById('lives').textContent = lives;
  document.getElementById('highScore').textContent = highScore;
}
